package app.server.project.main.service.service;

import app.server.project.core.websocket.model.Online;
import app.server.project.core.websocket.model.WSOffline;
import app.server.project.main.service.db.dao.user.UserActiveDao;
import app.server.project.main.service.db.entity.statics.StaticsActiveEntity;
import app.server.project.main.service.db.entity.user.UserActiveEntity;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.IdUtil;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.event.EventListener;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;

@AllArgsConstructor
@Service
@Slf4j
public class UserActiveService {
    private UserActiveDao userActiveDao;

    @Async
    @EventListener(Online.class)
    public void onLogin(Online online) {
        UserActiveEntity activeEntity = this.userActiveDao.getInfoById(online.getUserId());
        activeEntity.setLastLoginTime(LocalDateTime.now());
    }

    @Async
    @EventListener(WSOffline.class)
    public void onOffline(WSOffline online) {
        UserActiveEntity activeEntity = this.userActiveDao.getInfoById(online.getUserId());
        activeEntity.setLastOfflineTime(LocalDateTime.now());
    }

    //@Scheduled(fixedRate = 5 * 1000)
    @Scheduled(cron = "0 0 0 * * ?")
    public void executeDailyTask() {
        log.info("开始统计昨日活跃人数");
        var time = DateUtil.yesterday();
        var start = DateUtil.beginOfDay(time);
        var end = DateUtil.endOfDay(start);
        StaticsActiveEntity.of(IdUtil.getSnowflakeNextId(),
                this.userActiveDao.countActive(DateUtil.toLocalDateTime(start), DateUtil.toLocalDateTime(end)),
                DateUtil.toLocalDateTime(start)
        );
    }


}
